<template>
	<view
		class="uv-collapse-item__content"
		:animation="animationData"
		ref="animation"
	>
		<view
			class="content-class"
			:id="elId"
			:ref="elId"
		><slot /></view>
	</view>
</template>

<script setup>
	import {ref, getCurrentInstance, watch} from 'vue'
	const props = defineProps({
		show: Boolean
	})
	const emit = defineEmits(['resize'])
	
	const { proxy } = getCurrentInstance()
	
	function _toolGetRect(selector, all) {
		return new Promise((resolve) => {
			uni.createSelectorQuery()
				.in(proxy)[all ? 'selectAll' : 'select'](selector)
				.boundingClientRect((rect) => {
					if (all && Array.isArray(rect) && rect.length) {
						resolve(rect)
					}
					if (!all && rect) {
						resolve(rect)
					}
				})
				.exec()
		})
	}
	
	function guid(len = 32, firstU = true, radix = null) {
		const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
		const uuid = []
		radix = radix || chars.length
	
		if (len) {
			// 如果指定uuid长度,只是取随机的字符,0|x为位运算,能去掉x的小数位,返回整数位
			for (let i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
		} else {
			let r
			// rfc4122标准要求返回的uuid中,某些位为固定的字符
			uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
			uuid[14] = '4'
	
			for (let i = 0; i < 36; i++) {
				if (!uuid[i]) {
					r = 0 | Math.random() * 16
					uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]
				}
			}
		}
		if (firstU) {
			uuid.shift()
			return `u${uuid.join('')}`
		}
		return uuid.join('')
	}
	
	function queryRect(){
		return new Promise(resolve => {
			_toolGetRect(`#${elId.value}`).then(size => {
				resolve(size)
			})
		})
	}
	function sleep(value = 30) {
		return new Promise((resolve) => {
			setTimeout(() => {
				resolve()
			}, value)
		})
	}
		
		
	const elId = ref(guid())
	
	const expanded = ref(false)
	
	const animationData = ref({})
	
	const animating = ref(false)
	
	watch(() => props.show, newData => {
		expanded.value = newData
		setContentAnimate()
	})
	
	async function setContentAnimate() {
		const rect = await queryRect()
		const height = expanded.value ? rect.height : 0
		animating.value = true
		emit('resize')
		const animation = uni.createAnimation({
			timingFunction: 'ease-in-out',
		});
		animation
			.height(height)
			.step({
				duration: 300,
			})
			.step()
		// 导出动画数据给面板的animationData值
		animationData.value = animation.export()
		// 标识动画结束
		sleep(300).then(() => {
			animating.value = false
		})
	}
</script>

<style lang="scss" scoped>
	.uv-collapse-item {

		&__content {
			height: 0;
		}
	}
</style>


<!-- <template>
	<view class="contbox" :class="{show: show}" :style="'height: ' + (show * 140) + 'rpx'">
		<view class="content">
			<slot />
		</view>
	</view>
</template>

<script setup>
	const props = defineProps({
		show: Boolean
	})
</script>

<style lang="scss" scoped>
	.contbox{height: 0; transition: 0.3s; overflow: hidden;}
	.contbox.show{ transition: 0.3s;}
	.content{overflow: hidden;}
</style> -->